package com.bus.core.manager.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bus.common.hibernate4.Updater;
import com.bus.core.dao.BusUserSiteDao;
import com.bus.core.entity.BusUser;
import com.bus.core.entity.BusUserSite;
import com.bus.core.manager.BusUserSiteMng;

@Service
@Transactional
public class BusUserSiteMngImpl implements BusUserSiteMng {
	@Transactional(readOnly = true)
	public BusUserSite findById(Integer id) {
		BusUserSite entity = dao.findById(id);
		return entity;
	}

	public BusUserSite update(BusUserSite bean) {
		Updater<BusUserSite> updater = new Updater<BusUserSite>(bean);
		bean = dao.updateByUpdater(updater);
		return bean;
	}

	public void updateByUser(BusUser user, Integer siteId, Byte step,
			Boolean allChannel) {
		Set<BusUserSite> uss = user.getUserSites();
		if (siteId == null || step == null || allChannel == null) {
			return;
		}
		// 只更新单站点信息
		for (BusUserSite us : uss) {
		}
	}

	public void updateByUser(BusUser user, Integer[] siteIds, Byte[] steps,
			Boolean[] allChannels) {
		Set<BusUserSite> uss = user.getUserSites();
		// 全删
		if (siteIds == null) {
			user.getUserSites().clear();
			for (BusUserSite us : uss) {
				dao.delete(us);
			}
			return;
		}
	}

	public int deleteBySiteId(Integer siteId) {
		return dao.deleteBySiteId(siteId);
	}

	private void delete(Collection<BusUserSite> coll, Set<BusUserSite> set) {
		if (coll == null) {
			return;
		}
		for (BusUserSite us : coll) {
			dao.delete(us);
			set.remove(us);
		}
	}

	public BusUserSite deleteById(Integer id) {
		BusUserSite bean = dao.deleteById(id);
		return bean;
	}

	public BusUserSite[] deleteByIds(Integer[] ids) {
		BusUserSite[] beans = new BusUserSite[ids.length];
		for (int i = 0, len = ids.length; i < len; i++) {
			beans[i] = deleteById(ids[i]);
		}
		return beans;
	}

	private BusUserSiteDao dao;

	@Autowired
	public void setDao(BusUserSiteDao dao) {
		this.dao = dao;
	}
}